package dao

import models.Tables._
import play.api.db.slick.{DatabaseConfigProvider, HasDatabaseConfigProvider}
import slick.jdbc.JdbcProfile
import tool.Pojo._

import javax.inject.Inject
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future

/**
 * Created by yz on 2017/6/1.
 */
class BrowseCellDao @Inject()(protected val dbConfigProvider: DatabaseConfigProvider) extends
  HasDatabaseConfigProvider[JdbcProfile] {

  import profile.api._

  type MyRow = BrowseCellRow
  val table = BrowseCell

  def insertAll(circallpositions: Seq[MyRow]) = db.run(table ++=
    circallpositions)

  def deleteAll() = db.run(table.delete)

  def selectAll = {
    db.run(table.result)
  }

  def selectDiffSamples: Future[Seq[String]] = {
    db.run(table.map(_.diffGroup).distinct.result).
      map(x => x.flatMap(_.split(",")).distinct.filter(_ != ""))
  }

  def selectHead10000 = {
    db.run(table.take(1000).result)
  }

  def selectAllCellTypes: Future[Seq[String]] = {
    db.run(table.map(_.cellType).distinct.result)
  }

  def selectAllCellOrigins: Future[Seq[String]] = {
    db.run(table.map(_.cellOrigin).distinct.result)
  }

  def selectAllName: Future[Seq[String]] = {
    db.run(table.map(_.cellName).distinct.result)
  }

  def selectAllByName(names: List[String]) = {
    db.run(table.filter(_.cellName.inSetBind(names)).result)
  }

  def selectByName(name: String) = {
    db.run(table.filter(_.cellName === name).result.head)
  }

  def selectAllDiffGroup = {
    db.run(table.map(_.diffGroup).distinct.result.map(_.toList))
  }

  def selectByData(data: CellData) = {
    val filterData = table.filterOpt(data.cellOrigins) { (x, ys) =>
      val allB = ys.map { y =>
        x.cellOrigin.like(s"%${y}%")
      }
      allB.reduceLeft((t, z) => t || z)
    }.filterOpt(data.cellTypes) { (x, ys) =>
      val allB = ys.map { y =>
        x.cellType.like(s"%${y}%")
      }
      allB.reduceLeft((t, z) => t || z)
    }.filterOpt(data.diffSamples) { (x, ys) =>
      val allB = ys.map { y =>
        x.diffGroup.like(s"%${y}%")
      }
      val b = data.diffSamplesMethod match {
        case "union" => allB.reduceLeft((t, z) => t || z)
        case "inter" => allB.reduceLeft((t, z) => t && z)
      }
      b
    }
    val sortSamples = filterData
    val f = sortSamples.result
    db.run(f)
  }


}
